Php.php
<?php
namespace Tlf\Scrawl\FileExt;
/**
* Integrate the lexer for PHP files
*/
class Php {
/**
* Parsed `$str` into an ast (using the Lexer)
* @param $str a string to parse
* @return array ast
*/
public function parse_str(string $str): array{
$lexer = new \Tlf\Lexer();
$lexer->addGrammar(new \Tlf\Lexer\PhpGrammar());
$ast = new \Tlf\Lexer\Ast('file');
$phpGram = new \Tlf\Lexer\PhpGrammarNew();
$lexer = new \Tlf\Lexer();
$lexer->debug = false;
$lexer->addGrammar($phpGram);
// the first directive we're listening for
$lexer->addDirective($phpGram->getDirectives(':php_open')['php_open']);
ob_start();
// runs the lexer with $ast as the head
$ast = $lexer->lex($str, $ast);
ob_end_clean();
return $ast->getTree();
}
/**
* use the ast to create docs using the classList template
*
* @return array of files like `['rel/path'=>'file content']`
*/
public function make_docs(array $ast){
$files = [];
$classes = $ast['class'] ?? $ast['namespace']['class'] ?? [];;
foreach ($classes as $class){
$out = $this->template('classList.php', ['Class'=>(object)$class]);
$path = $class['fqn'];
$path = str_replace('\\','/', $path).'.md';
$files['class/'.$path] = $out;
}
$traits = $ast['trait'] ?? $ast['namespace']['trait'] ?? [];;
foreach ($traits as $trait){
$out = $this->template('traitList.php', ['Class'=>(object)$trait]);
$path = $trait['fqn'];
$path = str_replace('\\','/', $path).'.md';
$files['trait/'.$path] = $out;
}
return $files;
}
/**
* Load a template file
*/
public function template($name, $args=[]){
extract($args);
ob_start();
$file = dirname(__DIR__,2).'/Template/'.$name;
require($file);
return ob_get_clean();
}
}